package com.meiyuetao.myt.md.web.action;

import java.util.ArrayList;
import java.util.List;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.web.view.OperationResult;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.md.entity.CommodityGroup;
import com.meiyuetao.myt.md.entity.CommodityGroupDetail;
import com.meiyuetao.myt.md.service.CommodityGroupDetailService;
import com.meiyuetao.myt.md.service.CommodityGroupService;
import com.meiyuetao.myt.sys.entity.DynaPropLine;
import com.meiyuetao.myt.sys.entity.DynaPropLineVal;
import com.meiyuetao.myt.sys.service.DynaPropLineService;
import com.meiyuetao.myt.sys.service.DynaPropLineValService;

@MetaData("CommodityGroupController")
public class CommodityGroupController extends MytBaseController<CommodityGroup, Long> {

    @Autowired
    private CommodityGroupService commodityGroupService;
    @Autowired
    private CommodityGroupDetailService commodityGroupDetailService;
    @Autowired
    private DynaPropLineValService dynaPropLineValService;

    @Autowired
    private DynaPropLineService dynaPropLineService;

    @Override
    protected BaseService<CommodityGroup, Long> getEntityService() {
        return commodityGroupService;
    }

    @Override
    protected void checkEntityAclPermission(CommodityGroup entity) {
        // TODO Add acl check code logic
    }

    @Override
    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "commodityGroupDetails");
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        if (bindingEntity.isNew()) {
            bindingEntity.setPartner(getLogonPartner());
        }
        return super.doSave();
    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @MetaData("行项数据")
    public HttpHeaders commodityGroupDetails() {
        List<CommodityGroupDetail> commodityGroupDetails = bindingEntity.getCommodityGroupDetails();
        setModel(buildPageResultFromList(commodityGroupDetails));
        return buildDefaultHttpHeaders();
    }

    public CommodityGroupDetail[] cgDetails1D = new CommodityGroupDetail[30];
    public CommodityGroupDetail[][] cgDetails2D = new CommodityGroupDetail[30][30];
    public Long[] id1D = new Long[30];
    public Long[][] id2D = new Long[30][30];

    @MetaData("商品组属性")
    public HttpHeaders props() {
        String objName = this.getParameter("objName");
        String objSid = this.getParameter("objSid");
        String propCode = this.getParameter("propCode");
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "objName", objName));
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "objSid", Long.valueOf(objSid)));
        List<DynaPropLineVal> dynaPropLineVals = dynaPropLineValService.findByFilters(groupPropertyFilter);
        DynaPropLine dynaPropLineRoot = dynaPropLineService.findByProperty("code", propCode);
        List<DynaPropLine> dynaPropLines = dynaPropLineRoot.getChildren();
        if (!CollectionUtils.isEmpty(dynaPropLines)) {
            for (DynaPropLine item : dynaPropLines) {
                this.addDynaPropLine(item, dynaPropLineVals);
            }
        }
        this.getRequest().setAttribute("dynaPropLineRoot", dynaPropLineRoot);
        return buildDefaultHttpHeaders("props");
    }

    private void addDynaPropLine(DynaPropLine item, List<DynaPropLineVal> dynaPropLineVals) {
        DynaPropLineVal grandtedLineVal = null;
        for (DynaPropLineVal dynaPropLineVal : dynaPropLineVals) {
            if ((dynaPropLineVal.getDisabled() == null || dynaPropLineVal.getDisabled() == false) && dynaPropLineVal.getDynaPropLine().getId().equals(item.getId())) {
                grandtedLineVal = dynaPropLineVal;
                break;
            }
        }
        if (grandtedLineVal == null) {
            grandtedLineVal = new DynaPropLineVal();
            grandtedLineVal.setDynaPropLine(item);
            grandtedLineVal.setPropVal(item.getDefaultValue());
            grandtedLineVal.setOrderRank(item.getOrderRank());

        }
        displayDynaPropLineVals.add(grandtedLineVal);
        if (item.getChildrenSize() > 0) {
            List<DynaPropLine> children = item.getChildren();
            for (DynaPropLine child : children) {
                this.addDynaPropLine(child, dynaPropLineVals);
            }
        }
    }

    @MetaData("商品组属性")
    public HttpHeaders props2() {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "objName", "COMMODITY_GROUP"));
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "objSid", bindingEntity.getId()));
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "disabled", false));
        List<DynaPropLineVal> dynaPropLineVals = dynaPropLineValService.findByFilters(groupPropertyFilter);
        DynaPropLine dynaPropLineRoot = dynaPropLineService.findByProperty("code", "IYOUBOX_COMMODITY_PROPS");
        List<DynaPropLine> dynaPropLines = dynaPropLineRoot.getChildren();
        if (!CollectionUtils.isEmpty(dynaPropLines)) {
            for (DynaPropLine item : dynaPropLines) {
                for (DynaPropLineVal dplv : dynaPropLineVals) {
                    if (dplv.getDynaPropLine().equals(item)) {
                        item.addExtraAttribute("checked", true);
                    }

                }
            }
        }
        setModel(buildPageResultFromList(dynaPropLines));
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders propChildren() {
        DynaPropLine dynaPropLine = dynaPropLineService.findOne(Long.valueOf(getParameter("dynaPropLineId")));
        List<DynaPropLine> dynaPropLines = dynaPropLine.getChildren();
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "objName", "COMMODITY_GROUP"));
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "objSid", bindingEntity.getId()));
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "disabled", false));
        List<DynaPropLineVal> dynaPropLineVals = dynaPropLineValService.findByFilters(groupPropertyFilter);
        if (!CollectionUtils.isEmpty(dynaPropLines)) {
            for (DynaPropLine item : dynaPropLines) {
                for (DynaPropLineVal dplv : dynaPropLineVals) {
                    if (dplv.getDynaPropLine().equals(item)) {
                        item.addExtraAttribute("checked", true);
                    }

                }
            }
        }
        setModel(buildPageResultFromList(dynaPropLines));
        return buildDefaultHttpHeaders();
    }

    @MetaData("商品组属性")
    public HttpHeaders saveProps() {
        if (!CollectionUtils.isEmpty(displayDynaPropLineVals)) {
            String objName = this.getParameter("objName");
            String objSid = this.getParameter("objSid");
            CommodityGroup commodityGroup = commodityGroupService.findOne(Long.valueOf(objSid));
            List<DynaPropLineVal> toSaveDynaPropLineVals = new ArrayList<DynaPropLineVal>();
            GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "objName", objName));
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "objSid", Long.valueOf(objSid)));
            List<DynaPropLineVal> dynaPropLineVals = dynaPropLineValService.findByFilters(groupPropertyFilter);
            for (DynaPropLineVal dynaPropLineVal : displayDynaPropLineVals) {
                if (BooleanUtils.toBoolean(dynaPropLineVal.getDynaPropLine().getExtraAttributesValue("checked"))) {// 勾选
                    DynaPropLineVal toSaveDynaPropLineVal = null;
                    for (DynaPropLineVal dbDynaPropLineVal : dynaPropLineVals) {
                        if (dbDynaPropLineVal.getDynaPropLine().getId().equals(dynaPropLineVal.getDynaPropLine().getId())) {
                            toSaveDynaPropLineVal = dbDynaPropLineVal;
                            break;
                        }
                    }
                    if (toSaveDynaPropLineVal == null) {
                        toSaveDynaPropLineVal = new DynaPropLineVal();
                        toSaveDynaPropLineVal.setDynaPropLine(dynaPropLineService.findOne(dynaPropLineVal.getDynaPropLine().getId()));
                        toSaveDynaPropLineVal.setObjName(objName);
                        toSaveDynaPropLineVal.setObjSid(Long.valueOf(objSid));
                    }
                    toSaveDynaPropLineVal.setPropVal(dynaPropLineVal.getPropVal());
                    toSaveDynaPropLineVal.setDynaPropLine(dynaPropLineService.findOne(dynaPropLineVal.getDynaPropLine().getId()));
                    toSaveDynaPropLineVal.setPropValExt1(dynaPropLineVal.getPropValExt1());
                    toSaveDynaPropLineVal.setPropValExt2(dynaPropLineVal.getPropValExt2());
                    toSaveDynaPropLineVal.setPropValFetchStrategy(dynaPropLineVal.getPropValFetchStrategy());
                    toSaveDynaPropLineVal.setOrderRank(dynaPropLineVal.getOrderRank());
                    toSaveDynaPropLineVal.setDisabled(Boolean.FALSE);
                    toSaveDynaPropLineVals.add(toSaveDynaPropLineVal);
                } else {// 取消勾选
                    for (DynaPropLineVal dbDynaPropLineVal : dynaPropLineVals) {
                        if ((dbDynaPropLineVal.getDisabled() == null || dbDynaPropLineVal.getDisabled() == false)
                                && dbDynaPropLineVal.getDynaPropLine().getId().equals(dynaPropLineVal.getDynaPropLine().getId())) {
                            dbDynaPropLineVal.setDisabled(Boolean.TRUE);
                            toSaveDynaPropLineVals.add(dbDynaPropLineVal);
                            break;
                        }
                    }
                }
            }
            for (DynaPropLineVal outterDynaPropLineVal : toSaveDynaPropLineVals) {
                for (DynaPropLineVal innerDynaPropLineVal : toSaveDynaPropLineVals) {
                    if (outterDynaPropLineVal.getDynaPropLine().getParent() != null
                            && outterDynaPropLineVal.getDynaPropLine().getParent().getId().equals(innerDynaPropLineVal.getDynaPropLine().getId())) {
                        outterDynaPropLineVal.setParent(innerDynaPropLineVal);
                        break;
                    }
                }
            }
            dynaPropLineValService.save(toSaveDynaPropLineVals);
            commodityGroupService.updateDetailsByProps(commodityGroup);
        }
        setModel(OperationResult.buildSuccessResult("保存成功"));
        return buildDefaultHttpHeaders();
    }

    private List<DynaPropLineVal> displayDynaPropLineVals = new ArrayList<DynaPropLineVal>();

    public List<DynaPropLineVal> getDisplayDynaPropLineVals() {
        return displayDynaPropLineVals;
    }

    public void setDisplayDynaPropLineVals(List<DynaPropLineVal> displayDynaPropLineVals) {
        this.displayDynaPropLineVals = displayDynaPropLineVals;
    }

    @MetaData("回显数据")
    public HttpHeaders findAllDetails() {
        // 取得必须维护的一维数组
        List<DynaPropLineVal> dPLVListX1D = commodityGroupDetailService.findOneArray(bindingEntity, 0);
        // 查找商品组对应的GroupCommodityDetail一维度数组,参数二表示GroupCommodityDetail.propLineValY是否存在
        // List<CommodityGroupDetail> cgDs1D =
        // commodityGroupDetailService.findCGDArray(bindingEntity, false);
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "commodityGroup", bindingEntity));
        groupPropertyFilter.append(new PropertyFilter(MatchType.NN, "propLineValX", true));
        groupPropertyFilter.append(new PropertyFilter(MatchType.NN, "propLineValY", false));
        List<CommodityGroupDetail> cgDs1D = commodityGroupDetailService.findByFilters(groupPropertyFilter);
        if (dPLVListX1D.size() > 0) {
            for (int i = 0; i < dPLVListX1D.size(); i++) {
                DynaPropLineVal dyplv = dPLVListX1D.get(i);
                Boolean exist = false;
                CommodityGroupDetail existCommodityGroupDetail = null;
                for (CommodityGroupDetail cgd : cgDs1D) {
                    if (cgd.getPropLineValX() != null && dyplv.equals(cgd.getPropLineValX()) && cgd.getCommodity() != null) {
                        existCommodityGroupDetail = cgd;
                        exist = true;
                        break;
                    }
                }
                if (exist) {
                    cgDetails1D[i] = existCommodityGroupDetail;
                } else {
                    CommodityGroupDetail cgDetail = new CommodityGroupDetail();
                    cgDetail.setCommodityGroup(bindingEntity);
                    cgDetail.setPropLineValX(dyplv);
                    cgDetails1D[i] = cgDetail;
                }

            }
        }
        // 取得按需维护的Y轴一维数组
        List<DynaPropLineVal> dPLVListY1D = commodityGroupDetailService.findOneArray(bindingEntity, 1);
        if (dPLVListY1D.size() > 0) {
            // 查找商品组对应的GroupCommodityDetail 二维度数组
            // List<CommodityGroupDetail> gcDs2D =
            // commodityGroupDetailService.findCGDArray(bindingEntity, true);
            GroupPropertyFilter groupPropertyFilter2 = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "commodityGroup", bindingEntity));
            groupPropertyFilter.append(new PropertyFilter(MatchType.NN, "propLineValX", true));
            groupPropertyFilter.append(new PropertyFilter(MatchType.NN, "propLineValY", true));
            List<CommodityGroupDetail> gcDs2D = commodityGroupDetailService.findByFilters(groupPropertyFilter2);
            if (dPLVListX1D.size() > 0 && dPLVListY1D.size() > 0) {
                for (int j = 0; j < dPLVListY1D.size(); j++) {
                    for (int i = 0; i < dPLVListX1D.size(); i++) {
                        DynaPropLineVal dyplvX = dPLVListX1D.get(i);
                        DynaPropLineVal dyplvY = dPLVListY1D.get(j);
                        Boolean exist = false;
                        CommodityGroupDetail existCommodityGroupDetail = null;
                        for (CommodityGroupDetail gcd : gcDs2D) {
                            if (dyplvX.equals(gcd.getPropLineValX()) && dyplvY.equals(gcd.getPropLineValY())) {
                                existCommodityGroupDetail = gcd;
                                exist = true;
                                break;
                            }
                        }
                        if (exist) {
                            cgDetails2D[j][i] = existCommodityGroupDetail;
                        } else {
                            CommodityGroupDetail cgDetail = new CommodityGroupDetail();
                            cgDetail.setCommodityGroup(bindingEntity);
                            cgDetail.setPropLineValX(dyplvX);
                            cgDetail.setPropLineValY(dyplvY);
                            cgDetails2D[j][i] = cgDetail;
                        }

                    }
                }

            }

        }
        this.getRequest().setAttribute("cgDetails2D", cgDetails2D);
        this.getRequest().setAttribute("cgDetails1D", cgDetails1D);
        this.getRequest().getSession().setAttribute("cgDetails1D", cgDetails1D);
        this.getRequest().getSession().setAttribute("cgDetails2D", cgDetails2D);

        return buildDefaultHttpHeaders("details");
    }

    public HttpHeaders saveDetails() {
        CommodityGroupDetail[] cgDs1D = (CommodityGroupDetail[]) this.getRequest().getSession().getAttribute("cgDetails1D");
        CommodityGroupDetail[][] cgDs2D = (CommodityGroupDetail[][]) this.getRequest().getSession().getAttribute("cgDetails2D");
        commodityGroupService.saveDetails(bindingEntity, cgDs1D, cgDs2D);
        setModel(OperationResult.buildSuccessResult("保存成功"));
        return buildDefaultHttpHeaders();
    }

    public CommodityGroupDetail[] getCgDetails1D() {
        return cgDetails1D;
    }

    public void setCgDetails1D(CommodityGroupDetail[] cgDetails1D) {
        this.cgDetails1D = cgDetails1D;
    }

    public CommodityGroupDetail[][] getCgDetails2D() {
        return cgDetails2D;
    }

    public void setCgDetails2D(CommodityGroupDetail[][] cgDetails2D) {
        this.cgDetails2D = cgDetails2D;
    }

    public Long[] getId1D() {
        return id1D;
    }

    public void setId1D(Long[] id1d) {
        id1D = id1d;
    }

    public Long[][] getId2D() {
        return id2D;
    }

    public void setId2D(Long[][] id2d) {
        id2D = id2d;
    }

}